package no.ntnu.idi.deid.patternmatching.search;

import no.ntnu.idi.deid.config.Constants;
import no.ntnu.idi.deid.decision.validators.DoseMatcher;
import no.ntnu.idi.deid.documentunits.Document;
import no.ntnu.idi.deid.documentunits.Section;
import no.ntnu.idi.deid.documentunits.Sentence;
import no.ntnu.idi.deid.documentunits.Token;
import no.ntnu.idi.deid.documentunits.TokenIterator;

//Search within a document and assigns a searchResult to each document

public class Search{
	protected Document document;
	
	public Search(Document d){
		document = d;
	}
	
	public void searchAllTokens() {
		TokenIterator tokenIterator = new TokenIterator(document);
		while(tokenIterator.hasNext()) {
			Token token = tokenIterator.next();
			if(!token.isSensitivityTagDecided()) {
				searchToken(token);
			}
			if(!token.hasSearchResult()) { 
				for(Token t: token.getInnerWords()) {
					searchToken(t);
					token.addSet(t.getCategoryTagSet());
				}
			}
		}
	}
	
	public static void searchToken(Token token) {
		TokenSearch tokenSearch = new TokenSearch(token);
		tokenSearch.searchInRegularExpressionDatabase();
		tokenSearch.wordSearchInDictionary();
		tokenSearch.searchInMedicalCodes();
	}
	
	public void searchAllSentences() {
		
		for(Section sec: document) {
			for(Sentence sentence: sec) {
				SentenceSearch sentenceSearch = new SentenceSearch(sentence);
				if (Constants.ENABLE_SIMSTRING) {
					sentenceSearch.runSimstring();
					}
				if(Constants.ENABLE_NGRAM) {
					sentenceSearch.nGramSearch(2);
					sentenceSearch.nGramSearch(3);
				}
			}
		}	
	}
	
	public void finalSearch() {
		for(Section sec: document) {
			for(Sentence sentence: sec) {
				new DoseMatcher().checkSentence(sentence);
				DoseMatcher.createMedicamentPhrase(sentence);
			}
		}
	}
}

